package com.design.strategy.gplt;

import com.alibaba.excel.EasyExcel;
import com.design.enums.ChannelSourceEnum;
import com.design.strategy.GpltSettlementDo;
import com.design.strategy.ParseChannelFileHandler;
import com.design.strategy.ParseChannelFileRequest;
import com.design.strategy.ParseFileResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;

/**
 * @author lijiaming
 * @version 1.0
 * @description  channelSource: GPLT
 * @date 2025/9/26 11:27
 */
@Slf4j
@Component
public class GpltParseFileHandler implements ParseChannelFileHandler {
//    @Autowired
//    private FileServiceImpl fileService;

    @Override
    public ParseFileResult fileHandle(ParseChannelFileRequest request) throws Exception {
        ParseFileResult result = new ParseFileResult();
        InputStream fileInputStream = null;
        try {
            //读取微软云上的文件流
            URL url = new URL(request.getFilePath());
            String pathUrl = url.getPath();
            String fileName = pathUrl.substring(pathUrl.indexOf("/", 1) + 1);
            fileName = URLDecoder.decode(fileName, "UTF-8");  //处理中文
            //读取文件流
            //fileInputStream = fileService.downloadFileByBlockBlock(fileName);
            //读取第二行，比对校验交易总笔数transactionsrCount
            //读取第三行
            EasyExcel.read(fileInputStream, GpltSettlementDo.class, new GpltExcelReadListener(0, 0, result, request)).headRowNumber(3).sheet().doRead();
        } catch (Exception e) {
            log.error("gplt settlement report 文件解析失败, filePath:{}, exception:{}", request.getFilePath(), e);
            throw e;
        } finally {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }
        return result;
    }

    @Override
    public String getChannelSource() {
        return ChannelSourceEnum.GPLT.getCode();
    }

}
